package com.example.bootdemo.config;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.GenericConverter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class StringToDateConverter implements GenericConverter {
    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return new HashSet<>(Arrays.asList(new ConvertiblePair(String.class, Date.class)));
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        if (sourceType.toString().equals("java.lang.String") && targetType.toString().equals("java.util.Date")) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String date = (String) source;
            try {
                return format.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (sourceType.toString().equals("java.util.Date") && targetType.toString().equals("java.lang.String")) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = (Date) source;
            return format.format(date);
        }
        return null;
    }

}
